package com.wang.weblog.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.weblog.admin.model.vo.tag.*;
import com.wang.weblog.admin.service.AdminTagService;

import com.wang.weblog.common.domain.dos.ArticleTagRelDO;
import com.wang.weblog.common.domain.dos.TagDO;
import com.wang.weblog.common.domain.mapper.ArticleTagRelMapper;
import com.wang.weblog.common.domain.mapper.TagMapper;
import com.wang.weblog.common.enums.ResponseCodeEnum;
import com.wang.weblog.common.exception.BizException;
import com.wang.weblog.common.model.vo.SelectRspVO;
import com.wang.weblog.common.utils.PageResponse;
import com.wang.weblog.common.utils.Response;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
@Slf4j
public class AdminTagServiceImpl extends ServiceImpl<TagMapper,TagDO> implements AdminTagService {

    @Resource
    private TagMapper tagMapper;
    @Resource
    private ArticleTagRelMapper articleTagRelMapper;

    /**
     * 添加标签
     * @param addTagReqVO
     * @return
     */
    @Override
    public Response addTag(AddTagReqVO addTagReqVO) {
        List<String> tags = addTagReqVO.getTags();
        List<TagDO> tagDOS = new ArrayList<>();
        tagDOS = tags.stream()
                .map(tagName -> TagDO.builder()
                        .name(tagName)
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .build()).collect(Collectors.toList());
        try {
            saveBatch(tagDOS);
        }catch (Exception e){
            log.warn("该标签已存在",e);
        }

        return Response.success();
    }

    /**
     * 标签分页数据查询
     * @param findTagPageListReqVO
     * @return
     */
    @Override
    public PageResponse findTagPageList(FindTagPageListReqVO findTagPageListReqVO) {
        Long current = findTagPageListReqVO.getCurrent();
        Long size = findTagPageListReqVO.getSize();
        String name = findTagPageListReqVO.getName();
        LocalDate startDate = findTagPageListReqVO.getStartDate();
        LocalDate endDate = findTagPageListReqVO.getEndDate();

        Page<TagDO> tagDOPage = tagMapper.selectPageList(current, size, name, startDate, endDate);

        List<TagDO> records = tagDOPage.getRecords();
        List<FindTagPageListRspVO> vos = null;
        if (!CollectionUtils.isEmpty(records)) {
            vos = records.stream().map(tagDO -> FindTagPageListRspVO.builder()
                    .id(tagDO.getId())
                    .name(tagDO.getName())
                    .createTime(tagDO.getCreateTime())
                    .articlesTotal(tagDO.getArticlesTotal())
                    .build()).collect(Collectors.toList());
        }
        return PageResponse.success(tagDOPage, vos);
    }

    /**
     * 删除标签
     * @param deleteTagReqVO
     * @return
     */
    @Override
    public Response deleteTag(DeleteTagReqVO deleteTagReqVO) {
        Long tagId = deleteTagReqVO.getId();
        ArticleTagRelDO articleTagRelDO = articleTagRelMapper.selectOneByTagId(tagId);
        // 校验该标签下是否有关联的文章，若有，则不允许删除，提示用户需要先删除标签下的文章
        if (Objects.nonNull(articleTagRelDO)){
            log.warn("==> 此标签下包含文章，无法删除，tagId: {}", tagId);
            throw new BizException(ResponseCodeEnum.TAG_CAN_NOT_DELETE);
        }
        int count = tagMapper.deleteById(tagId);
        return count == 1 ? Response.success():Response.fail(ResponseCodeEnum.TAG_NOT_EXISTED);
    }

    /**
     * 标签模糊查询
     * @param searchTagReqVO
     * @return
     */
    @Override
    public Response searchTag(SearchTagReqVO searchTagReqVO) {
        String key = searchTagReqVO.getKey();
        List<TagDO> tagDOS = tagMapper.selectByKey(key);
        List<SelectRspVO> vos = null;
        if (CollectionUtils.isNotEmpty(tagDOS)){
            vos = tagDOS.stream()
                    .map(tagDO->SelectRspVO.builder()
                            .value(tagDO.getName())
                            .label(tagDO.getId().toString())
                            .build()).collect(Collectors.toList());
        }
        return Response.success(vos);
    }

    /**
     * 查询标签 Select 列表数据
     * @return
     */
    @Override
    public Response findTagSelectList() {
        // 查询所有标签, Wrappers.emptyWrapper() 表示查询条件为空
        List<TagDO> tagDOS = tagMapper.selectList(Wrappers.emptyWrapper());

        List<SelectRspVO> vos = null;
        // DO 转 VO
        vos = tagDOS.stream()
                .map(tagDO -> SelectRspVO.builder()
                        .label(tagDO.getName())
                        .value(tagDO.getId())
                        .build()).collect(Collectors.toList());
        return Response.success(vos);
    }
}
